//
//  QRContactParser.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/17/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "QRContactParser.h"
#import "CoreDataManager.h"

NSString * const NAME_REG_EX = @"N:[^;]*";
NSString * const COMPANY_REG_EX = @"ORG:[^;]*";
NSString * const TEL_REG_EX = @"TEL:[^;]*";
NSString * const EMAIL_REG_EX = @"EMAIL:[^;]*";
NSString * const ADDR_REG_EX = @"ADR:[^;]*";
NSString * const URL_REG_EX = @"URL:[^;]*";

@implementation QRContactParser

- (QRContact *)qrContact {
    NSManagedObjectContext *context = [CoreDataManager sharedInstance].managedObjectContext;
    _qrContact = (QRContact *)[NSEntityDescription insertNewObjectForEntityForName:@"QRContact" inManagedObjectContext:context];
    _qrContact.content = _qrData;
    if ([self parse]) {
        return _qrContact;
    }
    // We delete it if the parsing was faulty
    [context deleteObject:_qrContact];
    return nil;
}

- (BOOL) parse {
    // Contact name
    _qrContact.contactName = [self valueForRegEx:NAME_REG_EX withOffset:2 trimLength:0];
    
    // Company
    _qrContact.company = [self valueForRegEx:COMPANY_REG_EX withOffset:4 trimLength:0];
    
    // Telephone
    _qrContact.phone = [self valueForRegEx:TEL_REG_EX withOffset:4 trimLength:0];
    
    // Email
    _qrContact.email = [self valueForRegEx:EMAIL_REG_EX withOffset:6 trimLength:0];
    
    // Address
    _qrContact.address = [self valueForRegEx:ADDR_REG_EX withOffset:4 trimLength:0];
    
    // Url
    _qrContact.website = [self valueForRegEx:URL_REG_EX withOffset:4 trimLength:0];
    _qrContact.website = [_qrContact.website stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    
    return _qrContact.contactName != nil && _qrContact.phone != nil;
}

@end
